package com.example.takeoff.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.takeoff.entity.user;
import com.example.takeoff.mapper.userMapper;
import com.example.takeoff.service.userService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;
@Component
public class tokenUtil
{

    private static userService staticuserService;
    @Resource
    private userService userService;

    @PostConstruct
    public void setUserService()
    {
        staticuserService = userService;
    }

    public static String genToken(String userid, String sign)
    {
        return JWT.create().withAudience(userid) // 将 user id 保存到 token 里面
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2)) //两小时后token过期
                .sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥
    }

    //获取当前用户信息
    public static user getCurrentUser()
    {
        try
        {
            HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
            String token = request.getHeader("token");
            if (StrUtil.isNotBlank(token))
            {
                String userid = JWT.decode(token).getAudience().get(0);
                LambdaQueryWrapper<user> qw = new LambdaQueryWrapper<>();
                qw.eq(user::getUserid, userid);
                return staticuserService.getOne(qw);
            }
        }
        catch (Exception e)
        {
            return null;
        }
        return null;
    }
}
